let floatingMenu = null;
let resultWindow = null;
// 添加一个变量保存最后一次选中的有效文本
let lastSelectedText = '';

// 创建悬浮菜单
function createFloatingMenu(x, y) {
  if (floatingMenu) {
    document.body.removeChild(floatingMenu);
  }

  // 获取所有菜单项，包括自定义菜单
  chrome.storage.sync.get({
    customMenus: []
  }, (items) => {
    floatingMenu = document.createElement('div');
    floatingMenu.className = 'sf-floating-menu';
    
    // 默认菜单项
    const defaultMenus = `
      <div class="sf-menu-item" data-action="translate">翻译</div>
      <div class="sf-menu-item" data-action="comment">评论</div>
      <div class="sf-menu-item" data-action="summarize">总结</div>
    `;
    
    // 自定义菜单项
    const customMenus = items.customMenus.map(menu => 
      `<div class="sf-menu-item" data-action="custom" data-prompt="${menu.prompt}">${menu.name}</div>`
    ).join('');
    
    floatingMenu.innerHTML = defaultMenus + customMenus;
    
    floatingMenu.style.left = `${x}px`;
    floatingMenu.style.top = `${y}px`;
    document.body.appendChild(floatingMenu);

    // 添加点击事件监听器
    floatingMenu.addEventListener('click', handleMenuClick);
  });
}

// 创建结果窗口
function createResultWindow(content) {
  if (resultWindow) {
    document.body.removeChild(resultWindow);
  }

  resultWindow = document.createElement('div');
  resultWindow.className = 'sf-result-window';
  resultWindow.innerHTML = `
    <div class="sf-result-header">
      <div class="sf-result-title">处理结果</div>
      <div class="sf-close-btn">✕</div>
    </div>
    <div class="sf-result-content"></div>
    <div class="sf-result-footer">
      <button class="sf-action-btn sf-copy-btn">
        <span>📋</span>复制
      </button>
      <button class="sf-action-btn sf-insert-btn">
        <span>📝</span>插入
      </button>
    </div>
  `;
  
  document.body.appendChild(resultWindow);

  const contentDiv = resultWindow.querySelector('.sf-result-content');
  contentDiv.textContent = content;

  // 添加拖动功能
  let isDragging = false;
  let currentX;
  let currentY;
  let initialX;
  let initialY;
  let xOffset = 0;
  let yOffset = 0;

  const header = resultWindow.querySelector('.sf-result-header');
  
  header.addEventListener('mousedown', dragStart);
  document.addEventListener('mousemove', drag);
  document.addEventListener('mouseup', dragEnd);

  function dragStart(e) {
    if (e.target.classList.contains('sf-close-btn')) return;
    initialX = e.clientX - xOffset;
    initialY = e.clientY - yOffset;
    isDragging = true;
  }

  function drag(e) {
    if (isDragging) {
      e.preventDefault();
      currentX = e.clientX - initialX;
      currentY = e.clientY - initialY;

      xOffset = currentX;
      yOffset = currentY;

      setTranslate(currentX, currentY, resultWindow);
    }
  }

  function dragEnd(e) {
    initialX = currentX;
    initialY = currentY;
    isDragging = false;
  }

  function setTranslate(xPos, yPos, el) {
    el.style.transform = `translate(${xPos}px, ${yPos}px)`;
  }

  // 添加复制功能
  resultWindow.querySelector('.sf-copy-btn').addEventListener('click', () => {
    navigator.clipboard.writeText(contentDiv.textContent).then(() => {
      const copyBtn = resultWindow.querySelector('.sf-copy-btn');
      copyBtn.textContent = '已复制';
      setTimeout(() => {
        copyBtn.innerHTML = '<span>📋</span>复制';
      }, 2000);
    });
  });

  // 添加插入功能
  resultWindow.querySelector('.sf-insert-btn').addEventListener('click', () => {
    const commentBox = document.querySelector('.comment-textarea[contenteditable="true"]');
    if (commentBox) {
      commentBox.textContent = contentDiv.textContent;
      // 触发输入事件
      commentBox.dispatchEvent(new Event('input', { bubbles: true }));
      
      // 设置焦点并滚动到评论框
      commentBox.focus();
      commentBox.scrollIntoView({ behavior: 'smooth', block: 'center' });
      
      // 关闭结果窗口
      document.body.removeChild(resultWindow);
      resultWindow = null;
    } else {
      const insertBtn = resultWindow.querySelector('.sf-insert-btn');
      insertBtn.textContent = '未找到评论框';
      setTimeout(() => {
        insertBtn.innerHTML = '<span>📝</span>插入';
      }, 2000);
    }
  });

  // 添加关闭功能
  resultWindow.querySelector('.sf-close-btn').addEventListener('click', () => {
    document.body.removeChild(resultWindow);
    resultWindow = null;
  });

  return contentDiv;
}

// 处理菜单点击
async function handleMenuClick(e) {
  const menuItem = e.target;
  if (!menuItem.classList.contains('sf-menu-item')) return;

  const action = menuItem.dataset.action;
  const customPrompt = menuItem.dataset.prompt;
  const textToProcess = lastSelectedText;
  
  let contentDiv = createResultWindow('正在处理...');
  
  // 发送消息给background script处理API调用
  chrome.runtime.sendMessage({
    type: 'processText',
    action: action,
    text: textToProcess,
    prompt: customPrompt
  });

  // 移除菜单
  document.body.removeChild(floatingMenu);
  floatingMenu = null;
}

// 监听来自background的消息
chrome.runtime.onMessage.addListener((message) => {
  if (!resultWindow) return;
  const contentDiv = resultWindow.querySelector('.sf-result-content');

  switch (message.type) {
    case 'streamUpdate':
      contentDiv.textContent = message.content;
      break;
    case 'streamComplete':
      contentDiv.textContent = message.content;
      break;
    case 'error':
      contentDiv.textContent = '错误: ' + message.error;
      if (message.showSettings) {
        setTimeout(() => {
          chrome.runtime.openOptionsPage();
        }, 2000);
      }
      break;
  }
});

// 监听选择文本事件
document.addEventListener('mouseup', (e) => {
  const selection = window.getSelection().toString().trim();
  
  if (selection) {
    // 更新最后一次选中的文本
    lastSelectedText = selection;
    
    // 记录选中文本日志
    console.log('用户选中文本:', {
      text: lastSelectedText,
      length: lastSelectedText.length
    });
    
    // 获取选中文本的位置
    const range = window.getSelection().getRangeAt(0);
    const rect = range.getBoundingClientRect();
    
    // 显示悬浮菜单
    createFloatingMenu(
      e.pageX,
      e.pageY
    );
  } else if (floatingMenu && !floatingMenu.contains(e.target)) {
    // 记录菜单关闭日志
    console.log('关闭悬浮菜单');
    
    // 点击其他地方时关闭菜单
    document.body.removeChild(floatingMenu);
    floatingMenu = null;
  }
}); 